<?php
/*
 * 拼团
 */
namespace app\home\controller;

use app\common\controller\IndexBase;
use think\facade\Session;
use think\facade\Db;

class Reward extends IndexBase
{
    protected function initialize()
    {
        parent::initialize();
    }

    public function lists()
    {
        $result = Db::table('reward')->Distinct(true)->field('big_wheel')->column('big_wheel');
        $data = [];
        foreach ($result as $key => $v){
            //如果记录为真。跳出循环
            $show = Db::table('reward')->where(['big_wheel'=>$v])->wherein('status',[2,3])->count('id');
            if(empty($show)){
                $rs = Db::table('reward')->where(['big_wheel'=>$v])->order('id','DESC')->find();
                $total_reserve = intval(($rs['total_left']-$rs['company'])*0.6-$rs['reserve']);//本场剩余额度
                if ($rs['start_time']>time() && $rs['surplus']>0 && $total_reserve>0) {
                    $data[$key]['flag'] = 1;//预约
                }elseif($rs['start_time']<time() && $rs['surplus']>0){
                    $data[$key]['flag'] = 2;//抢购
                }else{
                    $data[$key]['flag'] = 0;//抢购
                }
                $data[$key]['code'] = $this->hashids->encode($v);
                $data[$key]['num'] = $v;
            }
        }
        // halt($data);
        $banner = Db::table('advert')->where(['ad_cat_id'=>3,'status'=>1])->select();
        return $this->fetch('',['data'=>$data,'banner'=>$banner]);
    }
    /*
     * 校验开发者服务器
     */
    public function index()
    {
        $uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect('/login.html');
        $code = $this->request->param('code');
        $big = $this->hashids->decode($code);
        !$big && $this->error('参数错误！');
        $data = Db::table('reward')->where(['big_wheel'=>$big])->wherein('status',[0,2])->order('id','DESC')->select()->toArray();
        // $ureserve = Db::table('user')->where(['id'=>$uid])->value('reserve');
        $info = Db::table('user')->field('integral,reserve')->where(['id'=>$uid])->find();
        foreach ($data as $key=>$v){
             // $data[$key]['bmax'] = intval($v['max']);
            if($v['max']>$info['integral']){
                $data[$key]['bmax'] = intval($info['integral']);
            }else{
                $data[$key]['bmax'] = intval($v['max']);
            }
            $reserve = intval($info['reserve']/0.13);//用户预约额度
            $total_reserve = intval(($v['total_left']-$v['company'])*0.6-$v['reserve']);//本场剩余额度
            $data[$key]['flag'] = ($reserve>$total_reserve?($total_reserve>0?$total_reserve:0):($reserve>0?$reserve:0));//如果用户预约额度大于本场剩余额度时，则最多可购买本场剩余额度
            $data[$key]['show'] = $reserve && $v['start_time']>time()?$reserve:0;//如果用户预约额度大于0时，则显示预约功能
            $buy = $v['start_time']>time() && empty($v['status']) ?intval($v['reserve']):intval($v['buy']);
            $data[$key]['ratio'] = $buy/$v['total_left']*100;
            $data[$key]['buy'] = $v['total_left']-$buy;
            $data[$key]['id'] = $this->hashids->encode($v['id']);
        }
        
        return $this->fetch('',['data'=>$data,'big'=>$big]);
    }
    /*
     *活动秒杀
     */
    public function buy()
    {
        set_time_limit(0);
        if ($this->request->isPost())
        {
            $uid = $this->hashids->decode(UserId());
            !$uid && $this->error('登陆超时',url('@login'));
            $param = $this->request->param();
            $num = abs($param['number']);
            // if(empty($param['type']) || $param['type'] !='reserve'){
            //     $mt_number = mt_rand(1,9);
            //     $mt_number%2 && $this->error('活动太火爆了,稍后再试！');
            // }
            $temp_code = $param['code'];
            $data = [];
            $code = $this->hashids->decode($temp_code);
            $data = Db::table('reward')->find($code);
            empty($data['is_frozen']) && $this->error('活动暂停中，请稍等...');
            $data['surplus'] <=0 && $this->error('本轮活动结束');
            $num<1 && $this->error('最少抢购一个');
            $data['surplus'] < $num && $this->error('本场剩余'.$data['surplus'].'个');
            $time = time();
            $data['end_time']<$time && $this->error('活动已结束，请等待下一场');
            $info = Db::table('user')->field('id,name,integral,reward_all,is_active,genes,parent_id,astrict,reserve,pay_pwd,salt')->where(['id'=>$uid,'status'=>1])->find();
            if($info['astrict']){
                $num > $data['max'] && $this->error('单次最多可买'.$data['max'].'个');
            }
            //执行秒杀操作
            $info['integral'] < $num && $this->error('可用积分最多可购买'.intval($info['integral']).'个');
            $rs = Db::table('reward_list')->field('create_time,update_time,id,user_id')->where(['user_id'=>$uid,'big_wheel'=>$data['big_wheel'],'small_wheel'=>$data['small_wheel'],'site'=>$data['site']])->find();//查询到记录
            if(isset($param['type']) && $param['type'] =='reserve'){
                !empty($rs)  && $this->error('每轮只能预约一次');
                //预约抢购
                $reserve = intval($info['reserve']/0.13);//用户预约额度
                $reserve<0 && $this->error('未获得预约资格！');
                $total_reserve = intval(($data['total_left']-$data['company'])*0.6-$data['reserve']);//本场剩余额度
                $total_reserve<0 && $this->error('本轮预约额度已抢完！');
                $reserve<$num && $this->error('预约额度剩余'.$reserve.'个！');
                $u_reserve_num = $num*0.13; //本次预约数量
                Db::table('user')->where(['id'=>$uid])->dec('reserve',$u_reserve_num)->update(['update_time'=>$time]);//扣除预约额度
            }else{
                empty($info['pay_pwd']) && $this->error('未设置支付密码！');
                $info['pay_pwd'] !== morse_code($param['pwd'],$info['salt']) && $this->error('支付密码错误！');
                $data['start_time']>$time && $this->error('活动未开始，请稍等');
            }
            // // 更新会员信息
            if(empty($info['is_active']) && ($info['reward_all']+$num>=10)){
                Db::table('user')->where(['id'=>$uid])->update(['active_time'=>$time,'is_active'=>1]);//修改会员激活状态
                Db::table('user')->where(['id'=>$info['parent_id']])->inc('tjnumber')->update();//增加上级推荐人
            }
            //计算推荐人奖励（直接、间接）
            $parent_total = $grandpa_total =0;
            if($info['parent_id']){
                $parent = Db::table('user')->field('tjnumber,parent_id')->where(['id'=>$info['parent_id'],'is_active'=>1,'is_lock'=>1,'status'=>1])->find();
                if (!empty($parent)) {
                    if($parent['tjnumber'] >=6){
                        $parent_total = $num*0.03;
                    }elseif($parent['tjnumber'] >=3){
                        $parent_total = $num*0.02;
                    }elseif($parent['tjnumber'] >=1){
                        $parent_total = $num*0.01;
                    }
                    if($parent['parent_id']){
                        $grandpa = Db::table('user')->where(['id'=>$parent['parent_id'],'is_active'=>1,'is_lock'=>1,'status'=>1])->value('tjnumber');
                        if($grandpa >=6){
                            $grandpa_total = $num*0.02;
                        }elseif($grandpa >=3){
                            $grandpa_total = $num*0.01;
                        }
                    }
                }
            }
            
            if(empty($rs)){ //新增
                $data = [
                    'user_id'       =>  $info['id'],
                    'name'          =>  $data['name'],
                    'user_name'     =>  $info['name'],
                    'big_wheel'     =>  $data['big_wheel'],
                    'small_wheel'   =>  $data['small_wheel'],
                    'site'          =>  $data['site'],
                    'is_check'      =>  $data['is_check'],
                    'max'           =>  $data['max'],
                    'total'         =>  $num,
                    'parent_id'     =>  $info['parent_id']??0,
                    'parent_total'  =>  $parent_total,
                    'grandpa_id'    =>  $parent['parent_id']??0,
                    'grandpa_total' =>  $grandpa_total,
                    'create_time'   =>  $time
                ];
                Db::table('reward_list')->insert($data);
            }else{  //修改
                if($info['astrict']){
                    if($rs['update_time']){
                        $time < $rs['update_time']+300 && $this->error('五分钟后再来吧！');
                    }else{
                        $time < $rs['create_time']+120 && $this->error('两分钟后再来吧！');
                    }
                }                
                Db::table('reward_list')->where(['site'=>$data['site'],'small_wheel'=>$data['small_wheel'],'big_wheel'=>$data['big_wheel'],'user_id'=>$uid])->inc('total',$num)->inc('parent_total',$parent_total)->inc('grandpa_total',$grandpa_total)->update(['update_time'=>$time]);
            }

            //扣除本轮记录
            Db::table('reward')->where(['id'=>$code])->inc('buy',$num)->inc('reserve',$num)->dec('surplus',$num)->update(['update_time'=>$time]);
            //扣除账户
            $acc_data =[
                'uid'           => $uid,
                'integral'      => '-'.$num,
                'change_desc'   => date('Y-m-d').'参与'.$data['name'].'活动',
                'change_type'   => 3
            ];
            insert_account_log($acc_data);//扣除账户
            $genes = $uid.','.$info['genes'];
            Db::table('user')->where(['id'=>$uid])->inc('reward_all',$num)->update(['update_time'=>$time]);//增加会员业绩
            Db::table('user')->wherein('id',$genes)->inc('team_performance',$num)->update(['update_time'=>$time]);//增加团队业绩
            $data = $info = $acc_data = $param = [];//释放
            Db::close();//释放数据链接
            $this->success('抢购成功');
        }

    }
    /*
     *查询当前已参与数量
     */
    public function get_code_num()
    {

        $uid = $this->hashids->decode(UserId());
        !$uid && $this->error('登陆超时',url('@login'));
        if ($this->request->isPost())
        {
            $param = $this->request->param();
            $code = $this->hashids->decode($param['code']);
            $data = Db::table('reward')->field('big_wheel,small_wheel')->find($code);
            empty($data) && $this->error('失败失败');
            $num = Db::table('reward_list')->where(['big_wheel'=>$data['big_wheel'],'small_wheel'=>$data['small_wheel'],'user_id'=>$uid])->value('total');
            $num = $num??0;
            $this->success('查询成功','',$num);
        }
    }

    
    

    //抢购记录
    public function log()
    {
        $uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect(url('@logout')); // 登录直接跳转
        $data = Db::table('reward_list')->where(['user_id'=>$uid])->order('create_time','DESC')->select();
        return $this->fetch('',['data'=>$data]);
    }
    /*
     *查询当前剩余数量
     */
    public function get_ratio()
    {

        $uid = $this->hashids->decode(UserId());
        !$uid && $this->error('登陆超时',url('@login'));
        if ($this->request->isPost())
        {
            $data = [];
            $res = Db::table('reward')->field('buy,total_left,id,start_time')->whereTime('start_time','<',time())->where('surplus','>',0)->where(['status'=>0])->select()->toArray();
            foreach ($res as $key => $v){
                $k = $this->hashids->encode($v['id']);
                if($v['start_time']==time()){
                    $buy = $v['start_time']>time()?0:intval($v['buy']*0.2);
                    $data[$k] = round($buy/$v['total_left']*100);
                    $data['buy'] = $v['total_left']-$buy;
                }elseif($v['start_time']+1==time()){
                    $buy = $v['start_time']>time()?0:intval($v['buy']*0.4);
                    $data[$k] = round($buy/$v['total_left']*100);
                    $data['buy'] = $v['total_left']-$buy;
                }elseif($v['start_time']+2==time()){
                    $buy = $v['start_time']>time()?0:intval($v['buy']*0.5);
                    $data[$k] = round($buy/$v['total_left']*100);
                    $data['buy'] = $v['total_left']-$buy;
                }elseif($v['start_time']+3==time()){
                    $buy = $v['start_time']>time()?0:intval($v['buy']*0.6);
                    $data[$k] = round($buy/$v['total_left']*100);
                    $data['buy'] = $v['total_left']-$buy;
                }elseif($v['start_time']+4==time()){
                    $buy = $v['start_time']>time()?0:intval($v['buy']*0.7);
                    $data[$k] = round($buy/$v['total_left']*100);
                    $data['buy'] = $v['total_left']-$buy;
                }elseif($v['start_time']+5==time()){
                    $buy = $v['start_time']>time()?0:intval($v['buy']*0.8);
                    $data[$k] = round($buy/$v['total_left']*100);
                    $data['buy'] = $v['total_left']-$buy;
                }elseif($v['start_time']+6==time()){
                    $buy = $v['start_time']>time()?0:intval($v['buy']*0.9);
                    $data[$k] = round($buy/$v['total_left']*100);
                    $data['buy'] = $v['total_left']-$buy;
                }else{
                    $buy = $v['start_time']>time()?0:intval($v['buy']);
                    $data[$k] = intval($buy/$v['total_left']*100);
                    $data[$k.'buy'] = $v['total_left']-$buy;
                }
            }
            $this->success('查询成功','',$data);
        }
    }

}
